package com.wing.cms.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wing.cms.dao.ArticleDao;
import com.wing.cms.dao.Article_groupDao;
import com.wing.cms.domain.Article;
import com.wing.cms.domain.Article_group;
import com.wing.common.util.ApplicationPath;
import com.wing.common.util.FileUtils;
import com.wing.common.util.GUID;
import com.wing.common.util.PageBean;
import com.wing.common.util.StringUtils;
import com.wing.lucene.ArticleIndex;

/**
 * 
 * @author djl
 * 
 */
@Service
@Transactional
public class ArticleManager {
	@Autowired
	private ArticleDao articledao;
	@Autowired
	private Article_groupDao article_groupDao;
	@Autowired
	private Article_groupManager article_groupManager;

	/**
	 * 获得该对象所有数据的列表
	 * 
	 * @return list
	 */
	public List<Map<String, Object>> findAll() {
		return articledao.findAll();
	}

	public PageBean findPageList(int currentPage, int pageSize, String siteId,
			String grpid, String s) {
		return articledao.findPageList(currentPage, pageSize, siteId, grpid, s);
	}

	/**
	 * 通过id得到对象
	 * 
	 * @param id
	 * @return pObject
	 * @throws IOException
	 */
	public Article findById(String id) throws IOException {
		Article article = articledao.findById(id);
		article.setContent(FileUtils.getFileString(ApplicationPath
				.getParameter("appRoot")
				+ "/" + article.getArticle_path()));
		return article;
	}

	/**
	 * 通过id得到对象
	 * 
	 * @param id
	 * @return pObject
	 * @throws IOException
	 */
	public String findContentById(String id) throws IOException {
		Article article = articledao.findById(id);
		return FileUtils.getFileString(ApplicationPath
				.getParameter("appRoot")
				+ "/" + article.getArticle_path());
	}

	/**
	 * 保存对象
	 * 
	 * @param article
	 * @param channelIds
	 * @throws IOException
	 */
	public void saveArticle(Article article, String grpIds, String sitePath)
			throws IOException {
		String[] ids = grpIds.split("\\|");
		if (article.getId() == null || "".equals(article.getId())) {
			article.setId(new GUID().toString());
			article.setArticle_path("site/" + sitePath + "/document/" + ids[0]
					+ "/" + article.getId() + ".html");
			articledao.insert(article);
			Article_group ag = new Article_group();
			ag.setArticle_id(article.getId());
			ag.setArtgroup_id(ids[0]);
			ag.setId(new GUID().toString());
			article_groupDao.insert(ag);
		} else {
			articledao.update(article);
			FileUtils.deleteFile(ApplicationPath.getParameter("appRoot") + "/"
					+ article.getArticle_path());
			// 删除索引里的文章
			ArticleIndex index = new ArticleIndex();
			index.deleteIndexByArtId(article.getId());
			 
			//处理文章分组
			List list =  article_groupManager.getArtgroupByArtId(article.getId());
			boolean flag=true;
			for(int i=0;i<list.size();i++){
				Map m = (Map)list.get(i);
				String grpid = (String)m.get("id");
				if(grpid.equals(ids[0])){
					flag=false;
				}else{
					article_groupDao.deleteArticle_groupByGrpIdArtIds(grpid,"'"+article.getId()+"'");
				}
			}
			if(flag){
				Article_group ag = new Article_group();
				ag.setArticle_id(article.getId());
				ag.setArtgroup_id(ids[0]);
				ag.setId(new GUID().toString());
				article_groupDao.insert(ag);
			}
		}

		FileUtils.saveFile(ApplicationPath.getParameter("appRoot") + "/"
				+ article.getArticle_path(), article.getContent());
		// 把文章索引**************************************************
		indexArticle(article);
		// for(int i=0;i<ids.length;i++){
		// if(ids[i].trim().equals("")){
		// continue;
		// }
		//			
		// }
	}

	/**
	 * 删除对象
	 * 
	 * @param chk
	 *            对象id数组
	 */
	public void deleteArticles(String[] chk, String sitePath) {

		for (int i = 0; i < chk.length; i++) {
			// 删除频道和文章的关联
			article_groupDao.deleteArticle_groupByArtId(chk[i]);
			// 删除这个文章对应的文件

			String articalPath = ApplicationPath.getParameter("appRoot")
					+ "/site/" + sitePath + "/document/";

			List list = article_groupManager.getArtgroupByArtId(chk[i]);
			// for(int j=0;j<list.size();j++){
			// Map map = (Map)list.get(j);
			// String path = articalPath+"/"+map.get("id")+"/"+chk[i]+".html";
			// FileUtils.deleteFile(path);
			// }
			Article article = articledao.findById(chk[i]);
			if (list.size() < 2) {
				FileUtils.deleteFile(ApplicationPath.getParameter("appRoot")
						+ "/" + article.getArticle_path());
				// 删除索引里的文章
				ArticleIndex index = new ArticleIndex();
				index.deleteIndexByArtId(article.getId());
			}

			articledao.delete(chk[i]);
		}
	}

	/**
	 * 通过一个频道id获得所有的文章
	 * 
	 * @param seachv
	 * 
	 * @param chk
	 *            对象id数组
	 */
	public PageBean findByGroupId(int currentPage, int pageSize,
			String groupId, String seachv) {
		return articledao.findByGroupId(currentPage, pageSize, groupId, seachv);
	}

	// 把一个站点的新闻，进行全文索引
	public void indexSite(String id) throws IOException {
		List<Map<String, Object>> articles = articledao.findBySiteId(id);
		ArticleIndex index = new ArticleIndex();
		index.deleteIndexBySiteId(id);
		for (int i = 0; i < articles.size(); i++) {
			Map art = articles.get(i);
			if (i == articles.size() - 1) {
				index.addIndex((String) art.get("id"), StringUtils
						.outHtmlString((String) art.get("art_name")),
						StringUtils.outHtmlString((String) art.get("summary")),
						StringUtils.outHtmlString((String) art.get("keyword")),
						StringUtils.outHtmlString((String) art.get("author")),
						StringUtils.outHtmlString(findContentById((String) art.get("id"))),
						(String) art.get("site_id"), true);
			} else {
				index.addIndex((String) art.get("id"), StringUtils
						.outHtmlString((String) art.get("art_name")),
						StringUtils.outHtmlString((String) art.get("summary")),
						StringUtils.outHtmlString((String) art.get("keyword")),
						StringUtils.outHtmlString((String) art.get("author")),
						StringUtils.outHtmlString(findContentById((String) art.get("id"))),
						(String) art.get("site_id"), false);
			}

		}
	}

	// 需要索引的内容不能为空
	private void indexArticle(Article article) {
		ArticleIndex index = new ArticleIndex();
		// System.out.println(article.getArt_name());
		// System.out.println(article.getSummary() );
		// System.out.println(article.getKeyword() );
		// System.out.println(article.getAuthor() );
		// System.out.println(article.getContent() );
		// System.out.println(article.getSite_id() );
		index.addIndex(article.getId(), StringUtils.outHtmlString(article
				.getArt_name()), StringUtils
				.outHtmlString(article.getSummary()), StringUtils
				.outHtmlString(article.getKeyword()), StringUtils
				.outHtmlString(article.getAuthor()), StringUtils
				.outHtmlString(article.getContent()), article.getSite_id(),
				true);
	}
}
